<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>编辑--${site.name}</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="description" content="${site.description}"/>
    <meta name="keywords" content="${site.keywords}"/>
    <meta name="author" content="${site.author}"/>
    <link rel="icon" href="${site.logo}">
    <link rel="stylesheet" href="${base}/static/layui/css/layui.css" media="all"/>
    <style type="text/css">
        .layui-form-item .layui-inline {
            width: 33.333%;
            float: left;
            margin-right: 0;
        }

        @media (max-width: 1240px) {
            .layui-form-item .layui-inline {
                width: 100%;
                float: none;
            }
        }

        .layui-form-item .role-box {
            position: relative;
        }

        .layui-form-item .role-box .jq-role-inline {
            height: 100%;
            overflow: auto;
        }

    </style>
</head>
<body class="childrenBody">
<form class="layui-form" id="form" lay-filter="form" style="width:80%;">
    <input value="" name="id" type="hidden">
    <input value="" name="videoUrl" id="videoUrl" type="hidden" lay-verify="checkUrl">
    <video id="videoattr" style="display: none" ></video>
    <div class="layui-form-item">
        <label class="layui-form-label">知识点名称</label>
        <div class="layui-input-block">
            <input type="text" autocomplete="off" class="layui-input submitlist" name="lorePointName" id="lorePointName" value=""
                   placeholder="请填写知识点名称" lay-verify="required">
            <input type="hidden" name="id" id="id">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">知识点描述</label>
        <div class="layui-input-block">
            <textarea name="lorePointDescribe" id="lorePointDescribe" placeholder="请填写知识点描述" lay-verify="required"
                      class="layui-textarea submitlist"></textarea>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">所属课程</label>
        <div class="layui-input-block">
            <select name="courseId" class="submitlist" id="courseId" lay-verify="required" lay-filter="course">
            </select>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">所属单元</label>
        <div class="layui-input-block">
            <select name="unitId"   class="submitlist" id="unitId" lay-verify="required" lay-filter="unit">
            </select>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">所属章节</label>
        <div class="layui-input-block">
            <select name="sectionId" class="submitlist" id="sectionId" lay-verify="required" lay-filter="section">
            </select>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">激活状态</label>
        <div class="layui-input-block">
            <select name="isActivated" class="submitlist" id="isActivated" lay-verify="required">
            </select>
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">知识点视频</label>
        <div class="layui-upload margin-left-110 layui-input-block">
            <div class="layui-btn-container">
                <button class="layui-btn  layui-btn-sm submitlist" type="button" id="selectvedio">选择文件</button>
            </div>
            <div class="layui-upload-list">
                <table class="layui-table">
                    <thead>
                    <tr>
                        <th>文件名</th>
                        <th>大小</th>
                        <th>状态</th>
                        <th>操作</th>
                    </tr>
                    </thead>
                    <tbody id="upList"></tbody>
                </table>
            </div>
        </div>
    </div>


    <div class="layui-form-item">
        <div class="layui-input-block">
            <button class="layui-btn submitlist" lay-submit="" lay-filter="addChLorePoint">立即提交</button>
            <button type="reset" class="layui-btn submitlist layui-btn-primary">重置</button>
        </div>
    </div>
</form>
<script type="text/javascript" src="${base}/static/layui/layui.js"></script>
<script type="text/javascript" src="${base}/static/js/qiniu.min.js"></script>
<script>
    layui.use(['form', 'jquery', 'layer', 'upload', 'table'
        ],

        function () {
            var form = layui.form,
                $ = layui.jquery, upload = layui.upload,
                layer = layui.layer;
            var lorePointData = top.lorePointData;

            //表单初始赋值
            form.val('form', {
                "id": lorePointData.id,
                "lorePointName": lorePointData.lorePointName,
                "lorePointDescribe": lorePointData.lorePointDescribe,
                "isActivated": lorePointData.isActivated,
                "videoUrl": lorePointData.videoUrl
            });
            form.verify({
                checkurl: function (value) {

                    if (value == "" || value == null) {
                        return "视频不能为空";
                    }
                }
            });

            /**
             * 加载状态
             */
            $.get("${base}/admin/system/dict/getDictByType/is_activated", {}, function (data) {
                var html = "";
                if (data.success === true) {
                    for (var i = 0; i < data.data.length; i++) {
                        html += '<option value="' + data.data[i].value + '">' + data.data[i].label + '</option>';
                    }
                    $("#isActivated").html(html);
                    //表单重新渲染
                    form.render();
                    form.val('form', {
                        "isActivated": lorePointData.isActivated
                    });
                }
            }, "json");

            /**
             * 反向加载 加载所属章节->单元->所属课程
             *
             */
            var courseId = "";
            var unitId = "";
            /*
            *加载章节
            */
            $.post("${base}/chSection/getSectionClass", {sectionId: lorePointData.sectionId}, function (data) {
                var html = "<option value=\"\">请选择对应单元</option>";
                for (var i = 0; i < data.length; i++) {
                    html += '<option value="' + data[i].id + '">' + data[i].sectionName + '</option>';

                }
                unitId = data[0].unitId;
                $("#sectionId").html(html);
                //表单重新渲染
                form.render();
                form.val("form", {
                    "sectionId": lorePointData.sectionId
                })
            }, "json");

            /**
             * 加载单元
             */
            $.post("${base}/chUnit/getUnitClass", {unitId: unitId}, function (data) {
                var html = "<option value=\"\">请选择对应单元</option>";
                for (var i = 0; i < data.length; i++) {
                    html += '<option value="' + data[i].id + '">' + data[i].unitName + '</option>';

                }
                courseId = data[0].courseId;
                $("#unitId").html(html);
                //表单重新渲染
                form.render();
                form.val("form", {
                    "unitId": unitId
                })
            }, "json");


            /**
             * 加载课程列表
             */
            $.post("${base}/chCourse/getCourseClass", {}, function (data) {
                var html = "";/*<option value="">请选择所属课程</option>*/
                for (var i = 0; i < data.length; i++) {
                    html += '<option value="' + data[i].id + '">' + data[i].courseName + '</option>';
                }
                $("#courseId").html(html);
                //表单重新渲染
                form.render();
                form.val("form", {
                    "courseId": courseId
                })
            }, "json");


            /**
             * 监听form-select事件
             */
            form.on("select(course)", function () {
                var courseId = $("#courseId").val();
                if (courseId == "") return false;
                /**
                 * 加载单元列表
                 */
                $.post("${base}/chUnit/getUnitClass", {courseId: courseId}, function (data) {
                    var html = "<option value=\"\">请选择单元</option>";
                    for (var i = 0; i < data.length; i++) {
                        html += '<option value="' + data[i].id + '">' + data[i].unitName + '</option>';
                    }
                    $("#unitId").html(html);
                    //表单重新渲染
                    form.render();
                }, "json");
            });
            /**
             * 监听form-select事件
             */
            form.on("select(unit)", function () {
                var unitId = $("#unitId").val();
                if (unitId == "") return false;
                /**
                 * 加载章节列表
                 */
                $.post("${base}/chSection/getSectionClass", {unitId: unitId}, function (data) {
                    var html = "<option value=\"\">请选择章节</option>";
                    for (var i = 0; i < data.length; i++) {
                        html += '<option value="' + data[i].id + '">' + data[i].sectionName + '</option>';
                    }
                    $("#sectionId").html(html);
                    //表单重新渲染
                    form.render();
                }, "json");
            });


            //初始化加载视频文件
            $.post("${base}/chLorePoint/getVideoUrl", {'id': lorePointData.id}, function (data) {
                if (data.success === true) {
                    $("#videoUrl").val(data.data);
                    var tr = $(['<tr id="upload-' + 0 + '">'
                        , '<td id="rename">' + data.data + '</td>'
                        , '<td>' + '未知' + 'kb</td>'
                        , '<td><span id="ok" style="color: #00db4f;">已上传</span></td>'
                        , '<td>'
                        , '<button type="button" class="layui-btn layui-btn-xs demo-up layui-btn-normal layui-btn-disabled" style="display: none">上传</button>'
                        , '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
                        , '</td>'
                        , '</tr>'].join(''));
                    $("#upList").append(tr);
                    //删除视频
                    tr.find('.demo-delete').on('click', function () {
                        uploadListIns.config.elem.next()[0].value = '';
                        $("#videoUrl").attr("value", "");
                        tr.remove();
                        $("#selectvedio").removeClass('layui-btn-disabled').removeAttr("disabled");
                        $.post("${base}/chLorePoint/deleteVideo", {
                            'key': data.data,
                            "id": lorePointData.id
                        }, function (data) {
                            if (data.success == true) layer.msg("删除成功");
                            else layer.msg(data.message)
                        });
                    });
                    $("#selectvedio").addClass('layui-btn-disabled').attr('disabled', "true");
                } else {
                    layer.msg(data.message);
                }
            }, 'json');

            //初始化文件上传事件（七牛云）
            var uploadListIns = upload.render({
                elem: "#selectvedio",
                accept: "video",
                multiple: false,
                auto: false,
                choose: function (obj) {
                    var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
                    //读取本地文件
                    obj.preview(function (index, file, result) {
                        var tr = $(['<tr id="upload-' + index + '">'
                            , '<td>' + file.name + '</td>'
                            , '<td>' + (file.size / 1014).toFixed(1) + 'kb</td>'
                            , '<td>等待上传</td>'
                            , '<td>'
                            , '<button type="button" class="layui-btn layui-btn-xs demo-up layui-btn-normal" style="display: none">上传</button>'
                            , '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
                            , '</td>'
                            , '</tr>'].join(''));

                        //单个上传
                        tr.find('.demo-up').on('click', function () {
                            //接收token
                            var token = "";
                            //接受随机文件名
                            var rondomName = "";
                            var suffix = file.name.substring(file.name.lastIndexOf("."), file.name.length);//获取文件后缀
                            // obj.upload(index, file);
                            $.ajax({
                                type: 'post',
                                url: "${base}/chLorePoint/getUploadToken",
                                data: {"suffix": suffix},
                                async: false,
                                dataType: 'json',
                                success: function (res) {
                                    console.log(res);
                                    if (res.success) {
                                        token = res.data.token;
                                        rondomName = res.data.filename;//随机文件名
                                    } else {
                                        layer.msg(res.message);
                                        delete files[index]; //删除对应的文件
                                        tr.remove();
                                        uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                                    }
                                }
                            });
                            fileUpload(index, file, token, rondomName);
                        });

                        //删除
                        tr.find('.demo-delete').on('click', function () {
                            $("#videoUrl").val("");
                            delete files[index]; //删除对应的文件
                            tr.remove();
                            $("#selectvedio").removeClass('layui-btn-disabled').removeAttr("disabled");
                            uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                        });
                        var num = index.split("-")[1];
                        num = parseInt(num);
                        if(num<1) {
                            var url = URL.createObjectURL(file);//把file转成URL
                            $('#videoattr').attr('src', url); //视频链接
                            $("#selectvedio").addClass('layui-btn-disabled').attr('disabled', "true");
                            $("#videoUrl").attr("value", "new");
                            $("#upList").append(tr);
                        }
                    });
                }
            });


            /**
             * 上传七牛云核心代码
             * @param index 文件下表
             * @param file  文件对象
             * @param token 凭证
             * @param randomName 接口生成的随机文件名，之后用来当作文件地址
             */
            function fileUpload(index, file, token, randomName) {
                $("#videoUrl").val(randomName);
                var fileName = file.name;                                //上传的本地文件绝对路径
                var size = file.size > 1024 ? file.size / 1024 > 1024 ? file.size / (1024 * 1024) > 1024 ? (file.size / (1024 * 1024 * 1024)).toFixed(2) + 'GB' : (file.size
                    / (1024 * 1024)).toFixed(2) + 'MB' : (file.size
                    / 1024).toFixed(2) + 'KB' : (file.size).toFixed(2) + 'B';		//文件上传大小
                var tr = $("#upList").find("tr#upload-" + index);
                var tds = tr.children();
                tds.eq(3).find(".demo-up").addClass('layui-btn-disabled').attr('disabled', "true");
                tds.eq(3).find(".demo-delete").addClass('layui-btn-disabled').attr('disabled', "true");
                //七牛云上传
                var observer = {                         //设置上传过程的监听函数
                    next(res) {                        //上传中(result参数带有total字段的 object，包含loaded、total、percent三个属性)
                        var upview = Math.floor(res.total.percent); //查看进度[loaded:已上传大小(字节);total:本次上传总大小;percent:当前上传进度(0-100)]
                        tds.eq(2).html('<span style="color: #c1c20c;">正在上传-(' + upview + '%) </span>');


                    },
                    error(err) {
                        tds.eq(2).html('<span style="color: #FF5722;">上传失败</span>');  //失败后
                        tds.eq(3).find(".demo-delete").removeClass("layui-btn-disabled").removeAttr("disabled");
                    },
                    complete(res1) {                      //成功后
                        //****:填写你的绑定域名或七牛云提供的测试域名
                        //?imageView2/2/h/100：展示缩略图，不加显示原图
                        tds.eq(0).html(randomName);
                        tds.eq(2).html('<span style="color: #00db4f;">上传成功</span>');
                        tds.eq(3).find(".demo-delete").removeClass("layui-btn-disabled").removeAttr("disabled");
                        $(".submitlist").removeClass('layui-btn-disabled').removeAttr('disabled', "true");
                        formData.field.videoUrl=randomName;
                        var video_time = document.getElementById("videoattr").duration;//视频时长
                        formData.field.videoTimeLong=parseInt(video_time);
                        //编辑知识点
                        $.post("${base}/chLorePoint/edit",formData.field, function (res) {
                            if (res.success) {
                                layer.msg("编辑成功！", {time: 1000}
                                );
                            } else {
                                layer.msg(res.message);
                            }
                        });
                    }
                };
                var putExtra = {
                    fname: randomName,                          //原文件名
                    params: {},                         //用来放置自定义变量
                    mimeType: null                      //限制上传文件类型
                };
                var config = {             //存储区域(z0: 代表华东;不写默认自动识别)
                    concurrentRequestLimit: 3            //分片上传的并发请求量
                };
                var observable = qiniu.upload(file, randomName, token, putExtra, config);
                observable.subscribe(observer)          // 上传开始
            }

            // $(".submitlist").addClass('layui-btn-disabled').attr('disabled', "true");
            var formData;
            form.on("submit(addChLorePoint)", function (data) {
                if($("#upList").find("tr").length>1){
                    layer.msg("只能上传一个视频！！！",{anim:6});
                    return false;
                }
                var videoUrl = $("#videoUrl").attr("value");
                if (videoUrl != "" && videoUrl != null && videoUrl != "new") {
                    $(".submitlist").addClass('layui-btn-disabled').attr('disabled', "true");
                    $.post("${base}/chLorePoint/edit", data.field, function (res) {
                        if (res.success) {
                            layer.msg("编辑成功！", {time: 1000}
                            );
                            $(".submitlist").removeClass('layui-btn-disabled').removeAttr('disabled', "true");
                        } else {
                            layer.msg(res.message);
                        }
                    });
                } else if (videoUrl =="new" ) { formData = data;
                    $(".submitlist").addClass('layui-btn-disabled').attr('disabled', "true");
                    $(".demo-up").click();
                } else {
                    layer.msg("视频不能为空！！", {anim: 6});
                }
                return false;
            });

        }
    );
</script>
</body>
</html>